﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.DependencyInjection;
using StyleMVVM.ViewModel;
#if !DOT_NET
using Windows.Devices.Geolocation;
#endif
#if NETFX_CORE
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

#else
using System.Windows;
using System.Windows.Controls;

#endif

namespace StyleMVVM.View.Regions
{
	public sealed class BaseRegionAdapter
	{
		internal static async Task<bool> CallNavigatingFrom(IRegion region, FrameworkElement oldExport)
		{
			if (oldExport != null && oldExport.DataContext is INavigationViewModel)
			{
				INavigationViewModel navigationViewModel = oldExport.DataContext as INavigationViewModel;

				StyleNavigatingCancelEventArgs args = new StyleNavigatingCancelEventArgs();

				await navigationViewModel.NavigatingFrom(oldExport, args);

				return args.Cancel;
			}

			return false;
		}

		protected void CallNavigatedTo(IRegion region, FrameworkElement newExport, object navigationParameter)
		{
			if (newExport != null)
			{
				IRegionAware regionAware = newExport.DataContext as IRegionAware;

				if (regionAware != null)
				{
					regionAware.Region = region;
				}

				if (newExport.DataContext is INavigationViewModel)
				{
					INavigationViewModel navigationViewModel = newExport.DataContext as INavigationViewModel;

					navigationViewModel.NavigationParameter = navigationParameter;

					navigationViewModel.NavigatedTo(newExport, new StyleNavigationEventArgs());
				}
			}
		}

		protected void CallNavigatedFrom(IRegion region, FrameworkElement oldExport)
		{
			if (oldExport != null)
			{
				IRegionAware regionAware = oldExport.DataContext as IRegionAware;

				if (regionAware != null)
				{
					regionAware.Region = region;
				}

				INavigationViewModel navigationViewModel = oldExport.DataContext as INavigationViewModel;

				if (navigationViewModel != null)
				{
					navigationViewModel.NavigatedFrom(oldExport, null);
				}
			}
		}
	}
}